﻿using System;
using System.Windows.Forms;
using Designer;

namespace Test
{
    public partial class Form1 : Form
    {

        DesignerHost host;
        public Form1()
        {
            InitializeComponent();

            var f = new Form();
            f.TopLevel = false;
            f.Visible = true;

            host = DesignerHost.CreateHost(f, d, (sender, e) => { propertyGrid1.SelectedObject = sender; });

            host.AddControl(new Label());

            panel1.Controls.Add(host);

            populateToolbox();
        }

        void populateToolbox()
        {
            foreach (var item in typeof(Label).Assembly.GetTypes())
            {
                if (item.BaseType != null)
                {
                    if (item.BaseType.Name == "Control" && !item.IsAbstract)
                    {
                        listBox1.Items.Add(item.Name);
                    }
                }
            }
        }
  
        private void d(object sender, DragEventArgs e)
        {
            var l = Activator.CreateInstance(getT("System.Windows.Forms." + listBox1.SelectedItem.ToString()));
            var lbl = (Control)l;
                lbl.AutoSize = true;
                lbl.Text = listBox1.SelectedItem.ToString();
                
                lbl.Location = new System.Drawing.Point(e.X, e.Y);

                host.AddControl(lbl);                
            
        }

        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            listBox1.DoDragDrop(listBox1.SelectedItem, DragDropEffects.All);
        }

        private Type getT(string fullname)
        {
            foreach (var item in typeof(Label).Assembly.GetTypes())
            {
                if (item.FullName == fullname)
                {
                    return item;
                }
            }
            return null;
        }
    }
}
